/*
 * Copyright (C) 2018 Logos Technology Ltd.
 */

package com.logos.common.update;

import android.content.Context;
import android.view.WindowManager;
import android.widget.Toast;

import com.logos.common.BuildConfig;
import com.logos.common.update.dialog.UpdateDialog;
import com.logos.common.update.entity.UpdateNetEntity;
import com.logos.tool.JsonUtil;
import com.logos.tool.log.LogUtil;
import com.google.gson.Gson;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by hk on 2018/6/25.
 * 注意：使用更新时注意主项目中的targetSdkVersion参数必须>=26,否则方法canRequestPackageInstalls在某些手机中会
 * 始终返回false，导致app无法自动安装。
 */
public class CheckUpdateUtil {

    /**
     * OnUpdateListener
     */
    public interface OnUpdateListener {

        /**
         * updateFail
         */
        void updateFail();

        /**
         * parseComplete
         *
         * @param isNew isNew
         */
        void parseComplete(boolean isNew);
    }

    /**
     * 检查更新
     *
     * @param context  context
     * @param listener listener
     */
    public static void checkUpdate(final Context context, final UpdateNetEntity updateNetEntity,
                                   final int versionCode, final OnUpdateListener listener) {

        UpdateManager.create(context).setUrl(updateNetEntity.getUrl()).setParser(new IUpdateParser() {
            @Override
            public UpdateInfo parse(String source) throws Exception {
                UpdateInfo info = new UpdateInfo();
                if (updateNetEntity.getIsForce() == 1) {
                    info.isForce = BuildConfig.IS_NEED_UPDATE;//测试版不强制更新
                } else {
                    info.isForce = false;
                }
                info.hasUpdate = true;
                info.updateContent = updateNetEntity.getUpdateContent();
                info.versionCode = updateNetEntity.getVersionCode();
                info.versionName = updateNetEntity.getVersionName();

                info.size = 1024;
                info.md5 = updateNetEntity.getMd5();
                info.url = updateNetEntity.getUrl();

                if (listener != null) {
                    listener.parseComplete(versionCode < info.versionCode);
                }
                return info;
            }
        }).setOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(UpdateError error) {
                if (listener != null) {
                    listener.updateFail();
                }
                LogUtil.error("updateError", LogUtil.getStackTrace(error));
                Toast.makeText(context,error.toString(),Toast.LENGTH_SHORT).show();
            }
        })
                .setPrompter(new IUpdatePrompter() {
                    @Override
                    public void prompt(IUpdateAgent agent) {
                        showDialog(agent,versionCode, context);
                    }
                })
                .setWifiOnly(false)
                .check();



//        String updateUrl = "common/version/info?version_code=" + appToken;
//        UpdateManager.create(context).setUrl(updateUrl)
//                .setParser(new IUpdateParser() {
//                    @Override
//                    public UpdateInfo parse(String source) throws Exception {
//                        LogUtil.debug("update", JsonUtil.formatJson(source));
//
//                        UpdateInfo info = new UpdateInfo();
//                        UpdateNetEntity model = new Gson().fromJson(source, UpdateNetEntity.class);
//                        UpdateNetEntity.DataBeanX.DataBean bean = model.getData().getData();
//                        if (bean.getIsForceUpgrade() == 1) {
//                            info.isForce = BuildConfig.IS_NEED_UPDATE;//测试版不强制更新
//                        } else {
//                            info.isForce = false;
//                        }
//                        info.hasUpdate = true;
//                        info.updateContent = bean.getDescription();
//                        info.versionCode = bean.getVersionCode();
//                        info.versionName = bean.getVersion();
//
//                        info.size = 1024;
//                        info.md5 = bean.getMd5();
//                        info.url = bean.getPackageUrl();
//
//                        if (listener != null) {
//                            listener.parseComplete(versionCode >= info.versionCode);
//                        }
//                        return info;
//                    }
//                })
//                .setOnFailureListener(new OnFailureListener() {
//                    @Override
//                    public void onFailure(UpdateError error) {
//                        if (listener != null) {
//                            listener.updateFail();
//                        }
//                        LogUtil.error("updateError", LogUtil.getStackTrace(error));
//                        Toast.makeText(context,error.toString(),Toast.LENGTH_SHORT).show();
//                    }
//                })
//                .setChecker(new IUpdateChecker() {
//                    @Override
//                    public void check(final ICheckAgent agent, String url) {
//                        handleNet(agent, url);
//                    }
//                })
//                .setPrompter(new IUpdatePrompter() {
//                    @Override
//                    public void prompt(IUpdateAgent agent) {
//                        showDialog(agent,versionCode, context);
//                    }
//                })
//                .setWifiOnly(false)
//                .check();
    }

    private static void handleNet(ICheckAgent agent, String url) {
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) new URL(BuildConfig.BASE_UPDATE_URL + url).openConnection();
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestMethod("GET");
            connection.connect();

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                agent.setInfo(UpdateUtil.readString(connection.getInputStream()));
            } else {
                agent.setError(new UpdateError(UpdateError.CHECK_HTTP_STATUS,
                        "" + connection.getResponseCode()));
            }
        } catch (IOException e) {
            e.printStackTrace();
            agent.setError(new UpdateError(UpdateError.CHECK_NETWORK_IO));
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private static void showDialog(final IUpdateAgent agent,int versionCode, final Context context) {
        UpdateInfo info = agent.getInfo();
        if (versionCode >= info.versionCode) {
            return;
        }
        final UpdateDialog dialog = new UpdateDialog(context, info.versionName,
                info.updateContent, info.isForce);
        dialog.setOnDialogClickListener(new UpdateDialog.DialogClickListener() {
            @Override
            public void onClickLater() {
                dialog.dismiss();
            }

            @Override
            public void onClickUpdate() {
                agent.update();
            }
        });
        try {
            dialog.show();
        } catch (WindowManager.BadTokenException e) {
            //use a log message
        }
    }
}
